package org.comparator4j;

import java.util.ArrayList;
import java.util.List;

import org.comparator4j.Comparator.Result;
import org.comparator4j.comparator.AbstractCollectionComparator;
import org.comparator4j.comparator.ArrayComparator;
import org.comparator4j.comparator.BasicComparator;
import org.comparator4j.comparator.NullComparator;

public class DefaultCompareContext implements CompareContext {
	private List<Comparator> comparators;
	private int index;

	public DefaultCompareContext() {
		index = 0;
		comparators = new ArrayList<Comparator>();
		register(new NullComparator());
		register(new BasicComparator());
		register(new ArrayComparator());
		register(new AbstractCollectionComparator());
	}

	public Result compare(Object o1, Object o2) throws CompareException {
		if (index < comparators.size()) {
			return comparators.get(index++).compare(o1, o2, this);
		} else {
			throw new CompareException("Cannot compare");
		}
	}

	public void register(Comparator comparator) {
		comparators.add(comparator);
	}

	public void reset() {
		index = 0;
	}

	public CompareContext newCompareContext() {
		DefaultCompareContext context = new DefaultCompareContext();
		context.comparators = comparators;
		return context;
	}
}
